<?php
declare ( strict_types = 0 );
namespace app\controller;

use think\facade\View;
use think\facade\Db;
use think\facade\Request;
use think\facade\Session;
use think\facade\Cache;
use app\model\CustomerModel;
use app\model\UserModel;
use app\model\DeptModel;
use app\Common;
use app\controller\Login;
use app\controller\Token;
use app\controller\Dept;
use app\controller\Sms;

class Customer {
    //常用数据表内容 及常用字典
    var $back = '<script>setTimeout(function(){history.back();},3000)</script>';
    var $dept = [];
    var $users = [];
    var $sex = [ 0=>'未知', 1=>'男', 2=>'女' ];
    var $type = array( '1'=>'一般客户', 2=>'重点客户' );
    var $status = array( '1'=>'正常', '2'=>'关闭', '3'=>'黑名单' );
    var $levels = array( 0=>'', '1'=>'★', '2'=>'★★', '3'=>'★★★', '4'=>'★★★★', '5'=>'★★★★★' );
    var $acc_type = array( 1=>'订单收款', 2=>'订单退款', 3=>'其它收款', 4=>'采购付款', 5=>'资产付款', 6=>'其它付款' );

    public function __construct() {
        $um = new UserModel();
        $this->users = $um->getAll();

        $dm = new DeptModel();
        $this->dept = $dm->getAll();

    }

    //找一人

    public function getOne( $name_or_mobile = '' ) {
        $uid = Session::get( 'logonid' );
        if ( !$name_or_mobile && empty( $uid ) ) return header( 'location:/index.php/login/index/target/admin' );

        $all = Request::param();

        if ( !empty( $all[ 'id' ] ) ) {
            $row = Db::table( 'customer' )->find( $all[ 'id' ] );
            if ( $row ) {
                return json( [ 'code'=>1, 'data'=>$row, 'msg'=>'找到会员,编号：'.$row[ 'id' ] ] );
            }
            return json( [ 'code'=>0, 'msg'=>'没找到任何信息.' ] );
        }

        //后台传参数查询
        if ( $name_or_mobile ) {
            $nm = trim( $name_or_mobile );

            $row = Db::query( 'select * from customer where name=? or mobile=?', [ $nm, $nm ] );
            if ( !count( $row ) ) return [ 'code'=>0, 'msg'=>'查无此人,手机:'.$name_or_mobile ];
            return [ 'code'=>1, 'data'=>$row[ 0 ] ];
        }

        if ( !empty( $all[ 'nameOrMobile' ] ) ) {
            $nm = trim( $all[ 'nameOrMobile' ] );

            $row = Db::query( 'select * from customer where name=? or mobile=?', [ $nm, $nm ] );
            if ( !count( $row ) ) {
                return json( [ 'code'=>0, 'msg'=>'【'.$all[ 'nameOrMobile' ].'】未找到相关人员!' ] );
            }

            $row[ 0 ][ 'level_name' ] = $this->levels[ $row[ 0 ][ 'level' ] ];
            return json( [ 'code'=>1, 'data'=>$row[ 0 ], 'msg'=>'人员找到，姓名：'.$row[ 0 ][ 'name' ].',编号：'.$row[ 0 ][ 'id' ] ] );
        }

        return json_encode( [ 'code'=>0, 'msg'=>'没找到任何信息！' ] );

    }

    public function index() {
        $uid = Session::get( 'logonid' );
        if ( empty( $uid ) ) return header( 'location:/index.php/login/index/target/admin' );

        $all = Request::param();

        $type_name = '客户';
        $page_limit = 20;
        $show_grid = 0;

        if ( !empty( $all[ 'show_grid' ] ) ) {
            $page_limit = 10;
            $show_grid = $all[ 'show_grid' ];
        }
        $list = Db::table( 'customer' );

        $type = '';
        if ( !empty( $all[ 'type' ] ) ) {
            $type = $all[ 'type' ];
            $list->where( 'type', $type );
        }

        //部门权限
        // $dept = new dept();
        // $my_depts = $dept->getMyDepts( $uid );
        // $arr = [];
        // $dept_id = '';
        // foreach ( $my_depts as $dept ) {
        //     $arr[] = $dept[ 'id' ];
        // }
        // if ( !empty( $all[ 'dept_id' ] ) ) {
        //     $dept_id = $all[ 'dept_id' ];
        //     if ( in_array( $dept_id, $arr ) ) {
        //         $arr = [ $dept_id ];
        //     } else {
        //         $arr = [];
        //     }
        // }

        // $my_depts = implode( ',', $arr );
        // $list->where( 'dept_id', 'in', $my_depts );

        //名字
        $name = '';
        if ( !empty( $all[ 'name' ] ) ) {
            $name = trim( $all[ 'name' ] );
            $list = $list->where( 'name', 'like', '%'.$name.'%' );
        }

        $mobile = '';
        if ( !empty( $all[ 'mobile' ] ) ) {
            $mobile = trim( $all[ 'mobile' ] );
            $list = $list->where( 'mobile', 'like', '%'.$mobile.'%' );
        }

        $list = $list->order( 'update_time', 'desc' )->paginate( $page_limit )->toArray();
        //halt( $this->cars );

        foreach ( $list[ 'data' ] as &$kv ) {
            $kv[ 'type_name' ] = $this->type[ $kv[ 'type' ] ];
            $kv[ 'creater_name' ] = $this->users[ $kv[ 'creater' ] ][ 'name' ];
            $kv[ 'dept_id_name' ] = $kv[ 'dept_id' ]>0? $this->dept[ $kv[ 'dept_id' ] ][ 'name' ] :'';
            $kv[ 'mobile2' ] = substr( $kv[ 'mobile' ], 0, 3 ).'****'.substr( $kv[ 'mobile' ], 7, 4 );
            //134 1234 1234
            $kv[ 'image' ] = empty( $kv[ 'image' ] )?'/upload/logo.png':$kv[ 'image' ];
            $kv[ 'status_name' ] = $this->status[ $kv[ 'status' ] ];
        }

        //halt( $list );
        View::assign(
            array(
                'list'=>$list,
                'type_name'=>$type_name,
                'types'=>$this->type,
                'name'=>$name,
                // 'dept_id'=>$dept_id,
                'mobile'=>$mobile,
                'status'=>$this->status,
                'show_grid'=>$show_grid,
                'type'=>$type
            )
        );
        return View::fetch( 'index' );
    }

    //编辑方法

    public function edit() {
        $uid = Session::get( 'logonid' );
        if ( empty( $uid ) ) return header( 'location:/index.php/login/index/target/admin' );

        $all = Request::param();

        if ( empty( $all[ 'id' ] ) ) return 'Invalid member id!'.$this->back;
        $id = $all[ 'id' ];

        $type = !empty( $all[ 'type' ] )?$all[ 'type' ]:'1';
        $view = 'customer_edit';

        $customer = new CustomerModel();
        $row = $customer->find( $id );

        //传入内容, 保存数据并跳转
        if ( !empty( $all[ 'mobile' ] ) && !empty( $all[ 'name' ] ) ) {

            $all[ 'update_time' ] = date( 'Y-m-d H:i:s' );
            if ( empty( $all[ 'dept_id' ] ) ) $all[ 'dept_id' ] = 1;

            $check = $this->input_check( $all );
            if ( !$check[ 'code' ] ) {
                return $check[ 'msg' ].$this->back;
            }

            //跟进记录处理
            if ( !empty( $all[ 'follow_memo' ] ) ) {
                $follow = array(
                    'customer_id'=>$row[ 'id' ],
                    'user_id'=>$uid,
                    'memo'=>$all[ 'follow_memo' ],
                    'create_time'=>date( 'Y-m-d H:i:s' )
                );
                Db::table( 'follow_log' )->insert( $follow );
            }

            unset( $all[ 'follow_memo' ] );
            //halt( $row[ 'dept_id' ] == $all[ 'dept_id' ], $row[ 'trainer' ] == $all[ 'trainer' ] );
            //保存
            Db::table( 'customer' )->save( $all );
            $loc = 'location:/index.php/customer/index/';

            //删除旧照片
            if ( !empty( $_FILES[ 'file' ][ 'size' ] ) ) {
                if ( $row[ 'image' ] ) Common::rm_file( $row[ 'image' ] );
            }

            //分配记录处理
            if ( $all[ 'sales' ] != $row[ 'sales' ] ) {
                $sales_name = Db::table( 'user' )->where( 'id', $all[ 'sales' ] )->value( 'name' );
                $old_sales = $this->users[ $row[ 'sales' ] ][ 'name' ];
                $allocate_log = array(
                    'customer_id'=>$row[ 'id' ],
                    'user_id'=>$uid,
                    'memo'=>'业务人员:'.$old_sales.'==>'.$sales_name,
                    'create_time'=>date( 'Y-m-d H:i:s' )
                );
                Db::table( 'allocate_log' )->insert( $allocate_log );
            }

            // return header( $loc );
        }

        //不传内容只有id, 查出本条数据 并进入编辑
        $row = $customer->find( $id );
        $sales_list = Db::query( "select id,name from user where status=1 and id<>1 and (group_id=1 or group_id in(select id from user_group where status=1 and name like '%销售%'))" );
        if ( !$row[ 'image' ] ) {
            $row[ 'image' ] = '/upload/logo.png';
        }
        $row[ 'status_name' ] = $this->status[ $row[ 'status' ] ];
        $user = Db::table( 'user' )->find( $uid );

        //halt( $sales_list );

        View::assign( [
            'status'=>$this->status,
            'type'=>$this->type,
            'data'=>$row,
            'status'=>$this->status,
            'user'=>$user,
            'sales_list'=>$sales_list

        ] );
        //halt( $row );
        return View::fetch( $view );
    }

    //客户新增

    public function customer_add() {
        $uid = Session::get( 'logonid' );
        if ( empty( $uid ) ) return header( 'location:/index.php/login/index/target/admin' );

        $all = Request::param();

        if ( !empty( $all[ 'mobile' ] ) && !empty( $all[ 'name' ] ) ) {
            if ( !empty( $all[ 'id' ] ) ) return 'ID重复!'.$this->back;
            if ( !$all[ 'name' ] ) return '无效的姓名!'.$this->back;

            $all[ 'mobile' ] = trim( $all[ 'mobile' ] );
            //$mobile = Common::is_mobile( $all[ 'mobile' ] );
            // if ( !$mobile ) {
            //     return '手机号码不正确！'.$this->back;
            // }

            $customer = new CustomerModel();
            $row = $customer::where( 'mobile', $all[ 'mobile' ] )->find();
            if ( !empty( $row ) ) return '手机号码已存在!  ['. $all[ 'mobile' ].']'.$this->back;

            $ct = date( 'Y-m-d H:i:s' );
            $all[ 'dept_id' ] = 1;
            $all[ 'creater' ]  = $uid;
            $all[ 'level' ] = 1;
            $all[ 'password' ] = substr( md5( '12345think' ), 0, 32 );
            $all[ 'create_time' ]  = $ct;
            $all[ 'status' ] = 1;

            $res = $customer->insert( $all );

            $loc = 'location:/index.php/customer/index';
            return header( $loc );

        }

        //销售列表
        $sales_list = Db::query( "select id,name from user where status=1 and id<>1 and (group_id=1 or group_id in(select id from user_group where status=1 and name like '%销售%'))" );
        View::assign( [
            'type'=>$this->type,
            'sales_list'=>$sales_list
        ] );

        return View::fetch( '/customer/customer_add' );
    }

    public function resetpwd( $id = '' ) {
        $uid = Session::get( 'logonid' );
        if ( empty( $uid ) ) return header( 'location:/index.php/login/target/admin' );

        $all = Request::param();

        if ( empty( $all[ 'id' ] ) ) return json_encode( [ 'code'=>0, 'msg'=>'invalid customer !' ] );
        $customer = new CustomerModel();

        $res = $customer->update( [ 'id'=>$all[ 'id' ], 'password'=>md5( '12345think' ) ] );
        return json( [ 'code'=>1, 'msg'=>'会员密码已初始化为：12345' ] );
        //header( 'location:/index.php/user' );
    }

    //客户端改密码

    public function resetpwd2() {
        $all = Request::param();

        if ( empty( $all[ 'mobile' ] ) ) {
            return json( [ 'code'=>0, 'msg'=>'请输入你注册的手机号码！' ] );
        }

        $customer = Db::table( 'customer' )->where( 'mobile', $all[ 'mobile' ] )->find();
        if ( !$customer ) {
            return json( [ 'code'=>0, 'msg'=>'你还没注册呢！' ] );
        }

        //----------短信验证码-----------------------------------//
        if ( empty( $all[ 'verify_code' ] ) || empty( $all[ 'password' ] ) ) {
            //
            return json( [ 'code'=>0, 'msg'=>'请输入短信验证码及新密码！' ] );
        }

        $sess_vcode = Cache::get( $all[ 'mobile' ] );
        if ( empty( $sess_vcode ) ) {
            return json( [ 'code'=>0, 'msg'=>'请先获取验证码！' ] );
        }

        if ( $all[ 'verify_code' ] != $sess_vcode ) {
            return json( [ 'code'=>0, 'msg'=>'验证码错误！' ] );
        }
        //----------短信验证码------------------------------------//

        $customer[ 'password' ] = md5( trim( $all[ 'password' ] ).'think' );
        Db::table( 'customer' )->update( $customer );

        return json( [ 'code'=>1, 'msg'=>'密码已修改！' ] );

    }

    public function logout( $target = 'index' ) {
        Session::delete( 'logonid' );
        Session::delete( 'uid' );
        Session::delete( 'uname' );
        Session::delete( 'utype' );
        return header( 'location:/index.php/login/customer_login' );
    }

    //学员之“我的”

    public function aboutme() {
        $all = Request::param();
        if ( empty( $all[ 'token' ] ) ) return json( [ 'code'=>0, 'msg'=>'Invalid token!' ] );

        $token = new Token();
        $arr = $token->check_token( $all[ 'token' ] );

        if ( $arr[ 'code' ]<1 ) {
            return json( $arr );
        }

        $customer = $arr[ 'customer' ];

        if ( !empty( $all[ 'update' ] ) ) {
            if ( empty( $all[ 'name' ] ) ) return json( [ 'code'=>0, 'msg'=>'name??' ] );
            $customer[ 'name' ] = $all[ 'name' ];

            if ( !empty( $_FILES[ 'file' ][ 'size' ] ) ) {
                $file = $this->check_file();
                $customer[ 'image' ] = $file[ 'msg' ];
            } else {
                $customer[ 'image' ] = $all[ 'file' ];
            }

            //halt( $customer, $all );
            $res = Db::table( 'customer' )->save( $customer );
            return json( [ 'code'=>$res, 'msg'=>'ok!', 'data'=>$customer ] );
        }

        return json( [ 'code'=>1, 'data'=>$customer ] );

    }

    //对输入的参数做一些检测

    private function input_check( &$all = [] ) {
        //手机号码检测
        $mobile = Common::is_mobile( $all[ 'mobile' ] );

        if ( !$mobile ) {
            //return [ 'code'=>0, 'msg'=>'手机号码不正确！' ];
        }
        $row = Db::table( 'customer' )->where( 'mobile', $all[ 'mobile' ] )->where( 'id', '<>', $all[ 'id' ] )->value( 'name' );
        if ( $row ) {
            return [ 'code'=>0, 'msg'=>'手机号码与:['.$row.'] 重复!' ];
        }

        if ( !empty( $all[ 'tel' ] ) ) {
            $all[ 'tel' ] = str_replace( '，', ',', strtoupper( str_replace( ' ', '', $all[ 'tel' ] ) ) );
        }

        if ( $_FILES[ 'file' ][ 'size' ]>0 ) {
            $files = Common::upload();
            if ( $files[ 'code' ] ) {
                $all[ 'image' ] = $files[ 'msg' ];
                return [ 'code'=>1 ];
            } else {
                return [ 'code'=>0, 'msg'=>'<h1>'.$files[ 'msg' ].'</h1>' ];
            }

        }
        return [ 'code'=>1 ];
    }

    //上传文件检测

    private function check_file() {

        if ( $_FILES[ 'file' ][ 'size' ]>0 ) {
            $files = Common::upload();

            if ( $files[ 'code' ] ) {
                //$all[ 'image' ] = $files[ 'msg' ];
                return [ 'code'=>1 ];
            } else {
                return [ 'code'=>0, 'msg'=>'<h1>'.$files[ 'msg' ].'</h1>' ];
            }
        }
        return [ 'code'=>0, 'msg'=>'no file post!' ];
    }

    //改密码

    public function change_pwd() {
        $all = Request::param();
        if ( empty( $all[ 'token' ] ) ) {
            return json( [ 'code'=>0, 'msg'=>'请登录!' ] );
        }

        $token = new Token();
        $arr = $token->check_token( $all[ 'token' ] );
        if ( !$arr[ 'code' ] ) {
            return json( $arr[ 'msg' ] );
        }

        $cust = $arr[ 'customer' ];
        //halt( $cust );

        if ( empty( $all[ 'pwd' ] ) || empty( $all[ 'pwd_2' ] ) ) {
            return json( [ 'code'=>0, 'msg'=>'密码错误!' ] );
        }

        $p = md5( $all[ 'pwd' ].'think' );
        if ( $p != $cust[ 'password' ] ) {
            return json( [ 'code'=>0, 'msg'=>'原密码错误！' ] );
        }

        $name = $cust[ 'name' ];
        if ( empty( $all[ 'name' ] ) ) {
            $name = $all[ 'name' ];
        }

        $arr = array( 'id'=>$cust[ 'id' ], 'name'=>$name, 'password'=>md5( $all[ 'pwd_2' ].'think' ) );

        $res = Db::table( 'customer' )->update( $arr );

        if ( $res ) return json( [ 'code'=>1, 'msg'=>'修改成功！' ] );

        return json( [ 'code'=>0, 'msg'=>'密码未修改！' ] );

    }

    //教练详情页

    public function customer_detail() {
        $all = Request::param();
        if ( empty( $all[ 'id' ] ) ) return json( [ 'code'=>0, 'msg'=>'缺少必要参数:id' ] );

        $data = Db::table( 'customer' )->find( $all[ 'id' ] );
        if ( !$data ) return json( [ 'code'=>0, 'msg'=>'没有资料!' ] );

        $assess = Db::table( 'assess' )->where( 'to', $data[ 'id' ] )->select()->toArray();
        foreach ( $assess as &$row ) {
            $row[ 'from_name' ] = Db::table( 'customer' )->where( 'id', $row[ 'from' ] )->column( 'name,image' );

        }
        $data[ 'assess' ] = $assess;

        return json( $data );

    }

}
